package com.tdam2011.grupo06.gui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.tdam2011.grupo06.R;
import com.tdam2011.grupo06.network.ResultParserSax;
import com.tdam2011.grupo06.network.XmlResultHandler;

public class SetPreferenceNombreUsuario extends Activity implements OnClickListener
{
	TextView usrname;
	TextView usrpass;
	boolean start;
	String resultInfo;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nombre_usuario);
        
        Bundle b = getIntent().getExtras();
        if(b==null) {start = true;}
        else {start = false;}
        
        if(start)
        {
        	SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this);
            if(myPreference.getString("nombreUsuario", "").compareTo("")!=0 && myPreference.getString("contrasenaUsuario", "").compareTo("")!=0)
    		{
            	this.finish();
            	startActivity(new Intent(this, Main.class));
    		}
        }
        Button buttonSetPreference = (Button)findViewById(R.id.btSetearUsuario);
        usrname = (TextView)findViewById(R.id.editTextNombre);
        usrpass = (TextView)findViewById(R.id.editTextContrasena);
        
        buttonSetPreference.setOnClickListener(this);
    }

	@Override
	protected void onResume() {
		super.onResume();
		
		SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this);
		usrname.setText(myPreference.getString("nombreUsuario", ""));
		usrpass.setText(myPreference.getString("contrasenaUsuario", ""));
	}

	public void onClick(View arg0) 
	{
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if(usrname.getText().toString().compareTo("")==0 || usrpass.getText().toString().compareTo("")==0)
		{
			showDialog(1);
		}
		else if (connectivityManager.getActiveNetworkInfo()==null)
		{
			showDialog(2);
		}
		else
		{
			ResultParserSax parser = new ResultParserSax();
			String result[] = parser.requestUserRegistration(usrname.getText().toString(), usrpass.getText().toString());
			resultInfo = result[1];
			int resultInt = Integer.parseInt(result[0]);
			if(resultInt == XmlResultHandler.resultCorrect)
			{
				SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this);
				SharedPreferences.Editor editor = myPreference.edit();
				editor.putString("nombreUsuario", usrname.getText().toString());
				String aux = usrpass.getText().toString();
				editor.putString("contrasenaUsuario", aux);
				editor.commit();
				this.finish();
				if(start) 
				{
					startActivity(new Intent(this, Main.class));
				}
				else
				{
					Toast.makeText(this, getResources().getString(R.string.prefGuardadas), Toast.LENGTH_SHORT).show();
				}
			}
			else
			{
				if(resultInt == XmlResultHandler.resultIncorrect)
				{
					showDialog(3);
				}
				else
				{
					showDialog(4);
				}
			}
		}
	}
	
	protected Dialog onCreateDialog(int id) 
	{
		Dialog dialog = null;
		if (id ==1) 
		{
			dialog = new AlertDialog.Builder(this).setIcon(R.drawable.ic_alert).setPositiveButton("Ok", null).setMessage(getResources().getString(R.string.errorPrefFaltantes)).setTitle("Error").create();
		}
		else if (id == 2)
		{
			dialog = new AlertDialog.Builder(this).setIcon(R.drawable.ic_alert).setPositiveButton("Ok", null).setMessage(getResources().getString(R.string.errorConexionPrefGuardar)).setTitle("Error").create();
		}
		else if (id == 3)
		{
			dialog = new AlertDialog.Builder(this).setIcon(R.drawable.ic_alert).setPositiveButton("Ok", null).setMessage(getResources().getString(R.string.errorPrefGuardar)+" "+resultInfo).setTitle("Error").create();
		}
		else if (id == 4)
		{
			dialog = new AlertDialog.Builder(this).setIcon(R.drawable.ic_alert).setPositiveButton("Ok", null).setMessage(getResources().getString(R.string.errorPrefExistente)).setTitle("Error").create();
		}
		else 
		{
			dialog = super.onCreateDialog(id);
		}
		return dialog;
	}
	
	protected void onPrepareDialog(int id, Dialog dialog) 
	{
		if(id == 3)
		{
			((AlertDialog) dialog).setMessage(getResources().getString(R.string.errorPrefGuardar)+" "+resultInfo);
		}
		super.onPrepareDialog(id, dialog);
	}

	/*@Override
	public void onBackPressed() 
	{
		if(!start) 
		{
			if(usrname.getText().toString().compareTo("")==0 || usrpass.getText().toString().compareTo("")==0)
			{
				showDialog(1);
			}
			else
			{
				SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this);
				SharedPreferences.Editor editor = myPreference.edit();
				editor.putString("nombreUsuario", usrname.getText().toString());
				String aux = usrpass.getText().toString();
				editor.putString("contrasenaUsuario", aux);
				editor.commit();
				this.finish();
				Toast.makeText(this, "Se ha guardado las preferencias", Toast.LENGTH_SHORT).show();
			}
		}
		else
		{
			super.onBackPressed();
		}
	}*/
}